package com.gopay.commons.validator;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Attribute;
import org.dom4j.Document;

import com.gopay.common.exception.validator.ValidatorTemplateCheckException;

/**
 * 验证文件合规检查
 * 
 * @ValidatorTemplateCheck.java
 * @author yaobo
 * @2012-12-26 上午09:53:31 www.gopay.com.cn Inc.All rights reserved.
 */
public class ValidatorTemplateCheck {
    private static final String SELECT_NODE_BY_NAME = "/forms/form/@name";

    /**
     * 验证文件合规检查
     * 
     * @param document
     * @return
     */
    public static boolean isValidatorCheck(Document document) {

        if (document == null) {
            return true;
        }

        boolean flag = false;
        try {
            flag = checkFormName(document);
            if (!flag) {
                return false;
            }
        } catch (ValidatorTemplateCheckException e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 验证formname是否重复
     * 
     * @param document
     * @return
     * @throws ValidatorTemplateCheckException
     */
    @SuppressWarnings("unchecked")
    private static boolean checkFormName(Document document) throws ValidatorTemplateCheckException {
        if (document == null) {
            return true;
        }

        Map<String, String> map = new HashMap<String, String>();
        List<Attribute> list = document.selectNodes(SELECT_NODE_BY_NAME);
        if (list == null || list.size() == 0) {
            return true;
        }

        Iterator<Attribute> it = list.iterator();
        Attribute attr = null;

        while (it.hasNext()) {
            attr = (Attribute) it.next();
            if (attr == null || StringUtils.isBlank(attr.getValue())) {
                throw new ValidatorTemplateCheckException("form name is null");
            }

            if (map.get(attr.getValue()) != null) {
                throw new ValidatorTemplateCheckException("form name is to many.");
            } else {
                map.put(attr.getValue(), attr.getValue());
            }
        }

        return true;
    }
}
